<?php
/**
 * 测试腾讯云短信服务连接 - 使用真实API
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-Type: application/json');

// 获取POST数据
$input = file_get_contents('php://input');
$data = json_decode($input, true);

if (!$data) {
    echo json_encode(['success' => false, 'message' => '无效的请求数据']);
    exit;
}

// 验证必填字段
$requiredFields = ['secret_id', 'secret_key', 'sdk_app_id', 'sign_name', 'template_id'];
foreach ($requiredFields as $field) {
    if (empty($data[$field])) {
        echo json_encode(['success' => false, 'message' => '请填写所有必填字段']);
        exit;
    }
}

$secretId = $data['secret_id'];
$secretKey = $data['secret_key'];
$sdkAppId = $data['sdk_app_id'];
$signName = $data['sign_name'];
$templateId = $data['template_id'];
$region = $data['region'] ?? 'ap-guangzhou';

// 基本验证
if (strlen($secretId) < 10) {
    echo json_encode(['success' => false, 'message' => 'SecretId格式不正确']);
    exit;
}

if (strlen($secretKey) < 10) {
    echo json_encode(['success' => false, 'message' => 'SecretKey格式不正确']);
    exit;
}

if (!is_numeric($sdkAppId)) {
    echo json_encode(['success' => false, 'message' => 'SDK AppID必须为数字']);
    exit;
}

try {
    // 调用腾讯云API查询短信发送统计（验证配置是否正确）
    $result = testTencentSmsConnection($secretId, $secretKey, $sdkAppId, $region);
    
    if ($result['success']) {
        echo json_encode(['success' => true, 'message' => '连接测试成功，配置有效']);
    } else {
        echo json_encode(['success' => false, 'message' => '连接失败：' . $result['message']]);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => '测试失败：' . $e->getMessage()]);
}

/**
 * 测试腾讯云短信连接
 */
function testTencentSmsConnection($secretId, $secretKey, $sdkAppId, $region) {
    $endpoint = 'sms.tencentcloudapi.com';
    $service = 'sms';
    $version = '2021-01-11';
    $action = 'SendStatusStatistics';
    $timestamp = time();
    $date = gmdate('Y-m-d', $timestamp);
    
    // 查询最近一天的发送统计
    $params = [
        'SmsSdkAppId' => $sdkAppId,
        'Limit' => 1,
        'Offset' => 0,
        'BeginTime' => time() - 86400,
        'EndTime' => time()
    ];
    
    $payload = json_encode($params);
    
    // 构造签名
    $algorithm = 'TC3-HMAC-SHA256';
    $canonicalRequest = "POST\n/\n\ncontent-type:application/json\nhost:" . $endpoint . "\n\ncontent-type;host\n" . hash('sha256', $payload);
    $credentialScope = $date . '/' . $service . '/tc3_request';
    $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
    $stringToSign = $algorithm . "\n" . $timestamp . "\n" . $credentialScope . "\n" . $hashedCanonicalRequest;
    
    $secretDate = hash_hmac('sha256', $date, 'TC3' . $secretKey, true);
    $secretService = hash_hmac('sha256', $service, $secretDate, true);
    $secretSigning = hash_hmac('sha256', 'tc3_request', $secretService, true);
    $signature = hash_hmac('sha256', $stringToSign, $secretSigning);
    
    $authorization = $algorithm . ' Credential=' . $secretId . '/' . $credentialScope . ', SignedHeaders=content-type;host, Signature=' . $signature;
    
    // 发送请求
    $headers = [
        'Authorization: ' . $authorization,
        'Content-Type: application/json',
        'Host: ' . $endpoint,
        'X-TC-Action: ' . $action,
        'X-TC-Timestamp: ' . $timestamp,
        'X-TC-Version: ' . $version,
        'X-TC-Region: ' . $region
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://' . $endpoint);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    if ($error) {
        return ['success' => false, 'message' => 'CURL错误：' . $error];
    }
    
    $result = json_decode($response, true);
    
    if ($httpCode !== 200) {
        return ['success' => false, 'message' => 'HTTP错误：' . $httpCode];
    }
    
    if (isset($result['Response']['Error'])) {
        $errorMsg = $result['Response']['Error']['Message'] ?? '未知错误';
        $errorCode = $result['Response']['Error']['Code'] ?? '';
        return ['success' => false, 'message' => $errorCode . ': ' . $errorMsg];
    }
    
    // 如果能正常返回，说明配置正确
    if (isset($result['Response']['SendStatusStatistics'])) {
        return ['success' => true, 'message' => '连接成功'];
    }
    
    return ['success' => true, 'message' => '配置验证通过'];
}
